//
//  LQBigPicturesViewController.swift
//  weiboLQ
//
//  Created by 半缘君 on 15/12/18.
//  Copyright © 2015年 banyuanjun.cn. All rights reserved.
//

import UIKit
import SVProgressHUD

private let LQPhotoBrowserViewCellID = "LQPhotoBrowserViewCellID"
class LQPhotoBrowserViewController: UIViewController {
    /// 选中的下标
    private var indexPath: NSIndexPath
    /// 选中的cell中的所有图片的地址
    private var thumb_URLs: [NSURL]?

    //MARK: - 构造函数
    init(indexPath:NSIndexPath,thumb_URLs:[NSURL]){
        self.indexPath = indexPath
        self.thumb_URLs = thumb_URLs
        super.init(nibName: nil, bundle: nil)//??
//        super.init()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //MARK: - 生命周期方法
    override func loadView() {
//        super.loadView()
        var rect = UIScreen.mainScreen().bounds
        rect.size.width += 20
        view = UIView(frame: rect)
//        view.backgroundColor = UIColor.blackColor()
        setupUI()
    }
    
    var onceToken:dispatch_once_t = 0

    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)

        dispatch_once(&onceToken) { () -> Void in
            
            self.collectionView.scrollToItemAtIndexPath(self.indexPath, atScrollPosition: UICollectionViewScrollPosition.CenteredHorizontally, animated: false)
        }

    }
    
    //MARK: - 懒加载控件
    /// colletion,使得页面能够翻页
    private lazy var collectionView:UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: LQBigPicturesFlowLayout())
    //取消按钮
    private lazy var cancelButton:UIButton = UIButton(title: "取消", backColor: UIColor.lightGrayColor())
    //保存按钮
    private lazy var saveBtn:UIButton = UIButton(title: "保存", backColor: UIColor.lightGrayColor())

    private class LQBigPicturesFlowLayout:UICollectionViewFlowLayout {
        private override func prepareLayout() {
            super.prepareLayout()
            var size = UIScreen.mainScreen().bounds.size
//            let size = view.bounds
            size.width += 20
            itemSize = size
//            print("itemSize\(itemSize)")
            //设置滚动方向
            minimumInteritemSpacing = 0
            minimumLineSpacing = 0
            scrollDirection = .Horizontal
            //设置分页
            collectionView?.pagingEnabled = true
            collectionView?.bounces = false
        }
    }
    
    
}


// MARK: - UI
extension LQPhotoBrowserViewController {
    /// 添加colletion,使得页面能够翻页
    private func setupUI () {
     addCollectionView()
        addButtons()
    }
    
    private func addCollectionView () {
        view.addSubview(collectionView)
        let rect = view.bounds
//        rect.size.width += 20
        collectionView.frame = rect
        //        collectionView.backgroundColor = UIColor.whiteColor()
        collectionView.dataSource = self
//         let tap = UITapGestureRecognizer(target: self, action: "tapGestureForCollectionView")
//        collectionView.addGestureRecognizer(tap)
        
        //注册cell
        collectionView.registerClass(LQPhotoBrowserViewCell.self, forCellWithReuseIdentifier: LQPhotoBrowserViewCellID)
    }
    
    private func addButtons () {
        view.addSubview(saveBtn)
        saveBtn.addTarget(self, action: "clickSave", forControlEvents:
                    UIControlEvents.TouchUpInside)
        
        saveBtn.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(view).offset(-8)
            make.right.equalTo(view).offset(-28)
            make.size.equalTo(CGSizeMake(100, 40))
        }
        view.addSubview(cancelButton)
        cancelButton.addTarget(self, action: "clickCancel", forControlEvents: UIControlEvents.TouchUpInside)
        cancelButton.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(view).offset(-8)
            make.left.equalTo(view).offset(8)
            make.size.equalTo(CGSizeMake(100, 40))
        }
    }
}
//
//extension LQPhotoBrowserViewController {
//    @objc private func tapGestureForCollectionView () {
//        dismissViewControllerAnimated(true, completion: nil)
//    }
//}

// MARK: - UICollectionViewDataSource
extension LQPhotoBrowserViewController:UICollectionViewDataSource {
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return thumb_URLs?.count ?? 0
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(LQPhotoBrowserViewCellID, forIndexPath: indexPath) as! LQPhotoBrowserViewCell
        
//        cell.backgroundColor = UIColor.redColor()
        cell.photoDelegate = self
        cell.imageURl = thumb_URLs![indexPath.item]
        return cell
    }
}
// MARK: - LQPhotoBrowserDismissDelegate
extension LQPhotoBrowserViewController:LQPhotoBrowserDismissDelegate {
    func imageViewForDismiss() -> UIImageView {
        let iv = UIImageView()
        
        iv.contentMode = .ScaleAspectFill
        iv.clipsToBounds = true
        
        let cell = collectionView.visibleCells()[0] as! LQPhotoBrowserViewCell
        
        iv.image = cell.imageV.image
        iv.frame = cell.scrollView.convertRect(cell.imageV.frame,
            toCoordinateSpace: UIApplication.sharedApplication().keyWindow!)
        
        print(iv)
        
        return iv
    }
    
    func indexPathForDismiss() -> NSIndexPath {
        return collectionView.indexPathsForVisibleItems()[0]
    
    }
}
// MARK: - 保存按钮和取消按钮
extension LQPhotoBrowserViewController {
        @objc private func clickSave () {
            //获取当前的图片
            let cell:LQPhotoBrowserViewCell = collectionView.visibleCells()[0] as! LQPhotoBrowserViewCell
            let image = cell.imageV.image
            guard let newImage = image else {
                return
            }
            UIImageWriteToSavedPhotosAlbum(newImage, self, "image:didFinishSavingWithError:contextInfo:", nil)

        }
    //    - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
    @objc private func image(image:UIImage,didFinishSavingWithError error:NSError?,contextInfo:AnyObject?){
        if error == nil {
            SVProgressHUD.showSuccessWithStatus("保存成功")
        } else {
            SVProgressHUD.showErrorWithStatus("保存失败")
        }
    }
    //点击取消按钮
        @objc private func clickCancel () {
            dismissViewControllerAnimated(true, completion: nil)
        }
}
extension LQPhotoBrowserViewController:LQPhotoBrowserViewCellDelegate {
    func photoBrowserViewDidTapToMiss() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    func photoBrowserViewDidScale(scale: CGFloat) {
        //是否隐藏
        let ishidden = (scale < 1)
        //隐藏
        if  ishidden {
            view.alpha = scale
            view.transform = CGAffineTransformMakeScale(scale, scale)
        } else {//不隐藏
            view.alpha = 1.0
            view.transform = CGAffineTransformIdentity
        }
        //设置其他控件的显隐
        hiddenOthersWithoutImage(ishidden)

        
    }
    private func hiddenOthersWithoutImage (isHidden:Bool) {
        self.saveBtn.hidden = isHidden
        self.cancelButton.hidden = isHidden
        collectionView.backgroundColor = isHidden ? UIColor.clearColor() : UIColor.blackColor()
    }
}
